/* eslint  react/no-string-refs: 0 */
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import moment from 'moment';
import { Grid, Table } from '@alifd/next';
import IconSvg from '#/components/IconSvg';
import { LineChart } from '#/components/Charts/';
import styles from './styles/styles';
import '#/scss/Global.scss';
import axios from 'axios'
import { ApiOfMonitorDayCount, ApiOfLatestMonitorData, ApiOfRealtimeMonitorData } from '#/utils/coreApiDefine'

const { Row, Col } = Grid;
const isNumber = (val) => {
  return Object.prototype.toString.call(val) === '[object Number]'
}
export default class Status extends Component {
  static displayName = 'Status';

  static propTypes = {};

  static defaultProps = {};

  constructor(props) {
    super(props);
    this.state = {
      baseInfo: {
        disabled: true,
      },
      gateway: {
        disabled: true,
      },
      collectGroup: {
        // executionCycle: '',
        metrics: []
      },
      todayMonitorCount: 0,
      yestodayMonitorCount: 0,
      lineChartData: [],
      lineChartDataLimit: 10,
      lineChartMetric: ''
    };

    this.timeoutId = -1;
  }

  componentWillReceiveProps(nextProps) {
    this.setState({
      baseInfo: nextProps.baseInfo,
      gateway: nextProps.gateway,
      collectGroup: nextProps.collectGroup
    })    
  }

  componentWillMount() {
    axios.all([ApiOfMonitorDayCount(this.props.deviceCode, 0), ApiOfMonitorDayCount(this.props.deviceCode, -1)])
    .then(axios.spread( (response1, response2) => {
      const todayMonitorCount = response1.data
      const yestodayMonitorCount = response2.data
      this.setState({
        todayMonitorCount,
        yestodayMonitorCount,
      })
    }));

    this.loadLatestMonitorData(this.props.deviceCode, this.state.lineChartDataLimit);
  }

  componentWillUnmount() {
    clearTimeout(this.timeoutId)
  }

  loadLatestMonitorData(resouceCode, limit) {
    ApiOfLatestMonitorData(resouceCode, limit).then(response => {
      const data = response.data;
      data.reverse();
      let availableMetrics = [];
      const lineChartData =  data.map(it=>{ 
        let metrics = JSON.parse(it.data);
        availableMetrics = Object.keys(metrics).filter(k=>!!metrics[k] && isNumber(metrics[k]))
        if(availableMetrics.length > 0) {
          return {xAxis: moment(it.collectedTime).format('HH:mm:ss'), yAxis: metrics[availableMetrics[0]], field:availableMetrics[0]} 
        }
      }).filter(it => !!it);
      this.setState({
        lineChartData,
        lineChartMetric: availableMetrics.length > 0 ? availableMetrics[0] : ''
      })

      /*if(!this.state.baseInfo.disabled && !this.state.gateway.disabled && this.state.collectGroup.executionCycle !== '') {
        this.loadRealtimeMonitorData(resouceCode);
      }*/
    })
  }

  /*loadRealtimeMonitorData(resouceCode) {
    const that = this;
    ApiOfRealtimeMonitorData(resouceCode).then(response => {
      const data = response.data;
      const metric = data.data.find(it=>it.code == that.state.lineChartMetric)
      let value = 0;
      if(metric) {
        value = metric['value'];
      }
      const point = {xAxis: moment(data.collectedTime).format('HH:mm:ss'), yAxis: value, field: that.state.lineChartMetric}
      let newPoints = [...that.state.lineChartData,  point]
      newPoints = newPoints.slice( newPoints.length > this.state.lineChartDataLimit ? newPoints.length - this.state.lineChartDataLimit : 0, newPoints.length);
      that.setState({
        lineChartData : newPoints
      })

      that.timeoutId = setTimeout(()=>{
        that.loadRealtimeMonitorData(resouceCode);
      }, that.state.collectGroup.executionCycle * 1000)
    })
  }*/

  onPlotDblClick(){
  }

  render() {

    const statusIcon = () => {
      let iconClass = "#icon-tingzhi";
      if(!this.state.baseInfo.disabled && !this.state.gateway.disabled) {
        iconClass = "#icon-yunhang";
      }
      return iconClass;
    }

    return (
      <div>
        <div style={styles.infoColumn}>
          <h5 style={styles.infoColumnTitle}>状态</h5>
           <Row gutter="20">
              <Col l="4">
                <IconSvg iconClass={statusIcon()} style={{ width: '8em', height: '8em', margin: '2em 0' }} />
              </Col>
              <Col l="8" style={styles.infoItem}>
                <div style={{ margin: "2em 0px" }}>
                  <dl className="dl-horizontal">
                    <dt>今日统计：</dt>
                    <dd>{this.state.todayMonitorCount}</dd>
                  </dl>
                  <dl className="dl-horizontal">
                    <dt>前日统计：</dt>
                    <dd>{this.state.yestodayMonitorCount}</dd>
                  </dl>
                </div>
              </Col>
              <Col l="6" style={styles.infoItem}>
                {/*<LineChart 
                  data= {this.state.lineChartData} 
                  xAxisVisible={false} 
                  legendVisible={false} 
                  height={200}
                  onPlotDblClick={this.onPlotDblClick.bind(this)}/>*/}
              </Col>
            </Row>
        </div>
        <div style={styles.infoColumn}>
          <h5 style={styles.infoColumnTitle}>功能区</h5>
            <Row gutter="20">
              <Col l="2" style={styles.infoItem}>
                <Link to={"/manage/device/" + this.props.deviceCode + '/cache'} style={{...styles.infoItemLink, marginTop: '20px'}}>
                  最新数据
                </Link>
              </Col>
              <Col l="2" style={styles.infoItem}>
                <Link to={"/manage/device/" + this.props.deviceCode + '/monitor'}  style={{...styles.infoItemLink, marginTop: '20px'}}>
                  实时视图
                </Link>
              </Col>
              <Col l="2" style={styles.infoItem}>
                <Link to={"/manage/device/" + this.props.deviceCode + '/chartview'} style={{...styles.infoItemLink, marginTop: '20px'}}>
                  数据视图
                </Link>
              </Col>
            </Row>
        </div>
      </div>
    );
  }
}
